package com.gaeainfo.modules.alarm.feedback.controller;

import com.gaeainfo.framework.core.basic.GaeaResourceProxy;
import com.gaeainfo.framework.core.basic.dto.BaseResponseDto;
import com.gaeainfo.framework.core.utils.common.GaeaCommonUtil;
import com.gaeainfo.modules.alarm.feedback.dto.FeedbackAttDto;
import com.gaeainfo.modules.alarm.feedback.dto.FeedbackDto;
import com.gaeainfo.modules.alarm.feedback.service.AlarmFeedbackService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Caven on 2018/7/10.
 */

@Controller
@RequestMapping("rest/alarm-feedback")
public class AlarmFeedbackController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AlarmFeedbackService alarmFeedbackService;

    @ResponseBody
    @RequestMapping(value = "generate-feedback", method = RequestMethod.POST)
    public BaseResponseDto generateFeedback(HttpServletRequest request) {
        try {
            FeedbackDto feedbackDto = this.resolveRequest(request);
            return BaseResponseDto.successtData(this.alarmFeedbackService.createFeedback(feedbackDto));
        } catch (Exception e) {
            logger.error(GaeaCommonUtil.getStackTrace(e));
            return BaseResponseDto.exception(e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "update-feedback", method = RequestMethod.POST)
    public BaseResponseDto updateFeedback(HttpServletRequest request) {
        try {
            FeedbackDto feedbackDto = this.resolveRequest(request);
            return BaseResponseDto.successtData(this.alarmFeedbackService.updateFeedback(feedbackDto));
        } catch (Exception e) {
            logger.error(GaeaCommonUtil.getStackTrace(e));
            return BaseResponseDto.exception(e);
        }
    }

    @ResponseBody
    @RequestMapping("get-feedback")
    public BaseResponseDto getFeedback(@RequestParam String processId) {
        try {
            return BaseResponseDto.successtData(this.alarmFeedbackService.getFeedback(processId));
        } catch (Exception e) {
            logger.error(GaeaCommonUtil.getStackTrace(e));
            return BaseResponseDto.exception(e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "delete-feedback-att", method = RequestMethod.POST)
    public BaseResponseDto deleteFeedbackAtt(@RequestBody String feedbackId,
                                             @RequestBody String fileId) {
        try {
            return BaseResponseDto.successtData(this.alarmFeedbackService.deleteFeedbackAtt(feedbackId, fileId));
        } catch (Exception e) {
            logger.error(GaeaCommonUtil.getStackTrace(e));
            return BaseResponseDto.exception(e);
        }
    }


    private FeedbackDto resolveRequest(HttpServletRequest request) throws Exception {
        String uploadPath = GaeaResourceProxy.getInstance().getStringByKey("feedback.att.upload.path", "system");
        FeedbackDto feedbackDto = new FeedbackDto();
        List<FeedbackAttDto> attList = new ArrayList<>();
        String feedbackId = request.getParameter("feedbackId");
        if (GaeaCommonUtil.isNullOrEmpty(feedbackId)) {
            feedbackId = GaeaCommonUtil.generateUUID("");
        }
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator it = multiRequest.getFileNames();
            while (it.hasNext()) {
                MultipartFile file = multiRequest.getFile(it.next().toString());
                if (file != null) {
                    String fileName = file.getOriginalFilename();
                    String folderPath = uploadPath + File.separator + feedbackId;
                    if (!GaeaCommonUtil.isNullOrEmpty(fileName)) {
                        String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                        if ("mp3" .equalsIgnoreCase(fileSuffix) || "avi" .equalsIgnoreCase(fileSuffix)) {
                            folderPath += File.separator + "audio";
                        } else if ("jpg" .equalsIgnoreCase(fileSuffix) || "png" .equalsIgnoreCase(fileSuffix)) {
                            folderPath += File.separator + "image";
                        }
                        File folder = new File(folderPath);
                        if (!folder.exists()) {
                            folder.mkdirs();
                        }
                        file.transferTo(new File(folderPath + File.separator + fileName));
                        FeedbackAttDto attDto = new FeedbackAttDto();
                        attDto.setFileName(fileName);
                        attDto.setFileType(fileSuffix);
                        attList.add(attDto);
                    }
                }
            }
        }
        feedbackDto.setFeedbackId(feedbackId);
        feedbackDto.setProcessId(GaeaCommonUtil.trimToEmpty(request.getParameter("processId")));
        feedbackDto.setDeptId(GaeaCommonUtil.trimToEmpty(request.getParameter("deptId")));
        feedbackDto.setDeptName(GaeaCommonUtil.trimToEmpty(request.getParameter("deptName")));
        feedbackDto.setPoliceNo(GaeaCommonUtil.trimToEmpty(request.getParameter("policeNo")));
        feedbackDto.setPoliceName(GaeaCommonUtil.trimToEmpty(request.getParameter("policeName")));
        feedbackDto.setSpaceTypeCode(GaeaCommonUtil.trimToEmpty(request.getParameter("spaceTypeCode")));
        feedbackDto.setSpaceTypeName(GaeaCommonUtil.trimToEmpty(request.getParameter("spaceTypeName")));
        feedbackDto.setResultTypeCode(GaeaCommonUtil.trimToEmpty(request.getParameter("resultTypeCode")));
        feedbackDto.setResultTypeName(GaeaCommonUtil.trimToEmpty(request.getParameter("resultTypeName")));
        feedbackDto.setAlarmLevel(GaeaCommonUtil.trimToEmpty(request.getParameter("alarmLevel")));
        feedbackDto.setReason(GaeaCommonUtil.trimToEmpty(request.getParameter("reason")));
        feedbackDto.setSituation(GaeaCommonUtil.trimToEmpty(request.getParameter("situation")));
        feedbackDto.setOnSite(GaeaCommonUtil.trimToEmpty(request.getParameter("onSite")).equals("1"));
        feedbackDto.setAttList(attList);
        return feedbackDto;
    }


}
